<template>
  <div class="app-container" style="overflow: hidden">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="归档号" prop="archiveNo">
        <el-input
          v-model="queryParams.archiveNo"
          placeholder="请输入归档号"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :data="roleList"
      :height="tableHeight"
    >
      <el-table-column
        label="归档号"
        prop="archiveNo"
        min-width="240"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="归档人"
        prop="createBy"
        min-width="240"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="归档时间"
        prop="createTime"
        min-width="240"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        :width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="onLook(scope.row.id)"
            >查看
          </el-button>
          <el-button
            size="mini"
            v-if="scope.row.auditStatus == 1 && proveType != 3"
            type="text"
            @click="onExport(scope.row)"
            v-hasPermi="
              proveType == 1 ? ['myarchived:print'] : ['archived:print']
            "
            >打印</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="proveType != 3"
            @click="onRemove(scope.row)"
            v-hasPermi="
              proveType == 1 ? ['myarchived:remove'] : ['archived:remove']
            "
            >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="proveType != 3"
            v-hasPermi="
              proveType == 1 ? ['myarchived:edit'] : ['archived:edit']
            "
            @click="onEdit(scope.row)"
            >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <detailModalVue ref="detailModalVue" @submit="handleQuery" />
    <closeModalVue ref="closeModalVue" @submit="handleQuery" />
    <finance ref="finance" @submit="handleQuery" />
    <casehandingModalVue ref="casehandingModalVue" @submit="handleQuery" />
    <el-dialog
      title="归档案件"
      :visible.sync="chivedDialog"
      width="1200px"
      append-to-body
    >
      <el-table :data="archivedList">
        <el-table-column
          label="案件名称"
          prop="caseName"
          :show-overflow-tooltip="true"
          width="150"
        >
          <template slot-scope="scope">
            <div
              v-if="scope.row.isConflict == '1' && proveType == 2"
              style="color: red"
            >
              {{ scope.row.caseName || scope.row.caseNo }}
            </div>
            <span v-else>
              {{ scope.row.caseName || scope.row.caseNo }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="案件分类"
          prop="status"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.categoryName
            }}{{
              scope.row.subCategoryName ? ">>" + scope.row.subCategoryName : ""
            }}
            {{
              scope.row.thirdCategoryName
                ? ">>" + scope.row.thirdCategoryName
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="收案时间"
          :show-overflow-tooltip="true"
          width="150"
          prop="receiptDate"
        />
        <el-table-column
          label="客户"
          :show-overflow-tooltip="true"
          width="150"
          prop="customerName"
        />
        <el-table-column
          label="对方当事人"
          :show-overflow-tooltip="true"
          width="150"
          prop="targetPartyName"
        />
        <el-table-column
          label="承办人员"
          :show-overflow-tooltip="true"
          width="150"
          prop="handlerName"
        />
        <el-table-column
          width="150"
          label="合同状态"
          prop="contractStatus"
          :formatter="formatter"
        />
        <el-table-column
          label="受理机构"
          :show-overflow-tooltip="true"
          prop="acceptOrgName"
          width="150"
        />
        <el-table-column
          label="受理案号"
          :show-overflow-tooltip="true"
          prop="acceptOrgNo"
          width="150"
        />
        <el-table-column
          label="归档日期"
          :show-overflow-tooltip="true"
          prop="archiveDate"
          width="150"
        />
        <el-table-column
          label="案件状态"
          :show-overflow-tooltip="true"
          prop="roleSort"
          width="150"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.case_state"
              :value="scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column label="审批结果" prop="auditStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.audit_status"
              :value="scope.row.auditStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          :width="80"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="openModal('detailModalVue', scope.row, 3)"
              >查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      title="归档编辑"
      :visible.sync="eidtDialog"
      width="450px"
      append-to-body
    >
      <el-form>
        <el-form-item label="归档号：">
          <el-input v-model="dataForm.archiveNo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="eidtDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave" :loading="upload.isUploading"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list } from "@/api/system/case";
import {
  archiveList,
  delcustomer,
  batchRemove,
  archivemine,
} from "@/api/case/case";
import finance from "../caseManage/financeModal.vue";
import detailModalVue from "../caseManage/detailModal.vue";
import closeModalVue from "../caseManage/closeModal.vue";
import casehandingModalVue from "../caseManage/casehandingModal.vue";
import { getToken } from "@/utils/auth";
import { download as $download } from "@/utils/request";
import { revoke, save, casesList } from "@/api/archived";
export default {
  name: "sealmanage",
  dicts: [
    "sys_normal_disable",
    "case_source",
    "approval_status",
    "case_state",
    "audit_status",
    "sys_carage_type",
  ],
  components: { detailModalVue, closeModalVue, finance, casehandingModalVue },
  computed: {
    tableHeight() {
      return this.$store.state.app.clientHeight - 50;
    },
  },
  data() {
    return {
      uploading: false,
      multipleSelection: [],
      eidtDialog: false,
      // 遮罩层
      loading: true,
      // 选中数组
      total: 0,
      // 角色表格数据
      roleList: [],
      dateRange: [], //搜索时间
      chivedDialog: false,
      tree: [],
      // 查询参数
      queryParams: {
        archiveNo: "",
        pageNum: 1,
        pageSize: 10,
        caseNo: undefined,
        caseName: undefined,
        customerName: undefined,
        handlerName: "",
        categoryId: "",
        status: "",
        auditStatus: "",
        orderByColumn: "updateTime",
        isAsc: "desc",
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/case/importData",
      },
      dataForm: {
        archiveNo: "",
        id: "",
      },
      archivedList: [],
    };
  },
  props: {
    proveType: {
      type: String,
      default: "0", // 0案件管理，1我的归档,3我的案件
    },
  },
  created() {
    this.getList();
    this.getTree();
    this.$root.$on("notice:case", (e) => {
      console.log("on notice =>>>>", e);
      this.$nextTick(() => {
        this.openModal("detailModalVue", e, 3);
      });
    });
  },
  mounted() {},
  methods: {
    onRemove(row) {
      this.$modal
        .confirm("是否撤回" + row.archiveNo + "的数据项？")
        .then(() => {
          revoke([row.id]).then((res) => {
            this.getList();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});
    },
    onSave() {
      this.loading = true;
      save(this.dataForm)
        .then((res) => {
          this.$message.success("保存成功");
          this.eidtDialog = false;
          this.getList();
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    onEdit(row) {
      this.dataForm.archiveNo = row.archiveNo;
      this.dataForm.id = row.id;
      this.eidtDialog = true;
    },
    onDelAll() {
      // 批量删除功能
      this.$modal.confirm("是否确认删除").then(() => {
        this.loading = true;
        const ids = this.multipleSelection.map((v) => v.id);
        batchRemove(ids)
          .then((res) => {
            if (ids.length === this.roleList.length) {
              let page = this.queryParams;
              page--;
              this.queryParams.page = page > 1 ? page : 1;
            }
            this.getList();
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    selectable(row) {
      return row.auditStatus != 0;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getTree() {
      //获取案件分类
      list().then((res) => {
        console.log(res);
        this.tree = res.data;
      });
    },
    formatter(row) {
      switch (row.contractStatus) {
        case 0:
          return "未提交";
        case 1:
          return "已提交";
        default:
          return row.contractStatus;
      }
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      let params = {
        orderByColumn: "updateTime",
        isAsc: "desc",
        // auditor: this.proveType === "0" ? "0" : "1",
        proveType: this.proveType,
        archived: 1,
      };
      this.multipleSelection = [];
      if (this.proveType === "3") {
        //我的归档
        archivemine({
          ...this.addDateRange(this.queryParams, this.dateRange),
          ...params,
        }).then((response) => {
          this.roleList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        archiveList({
          ...this.addDateRange(this.queryParams, this.dateRange),
          ...params,
        }).then((response) => {
          this.roleList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
      // this.$tab.refreshPage({ path: "caseManage" });
      // this.$tab.openPage("编辑案件", "addcaseManage");
    },
    //下载
    download(row, type) {
      let resource = `${row.url}`;
      this.$download.resource(resource);
    },
    handleImport() {
      this.upload.title = "案件导入";
      this.upload.open = true;
    },
    //新增
    onadd() {
      this.$router.push({
        path: "/caseManage/addcaseManage",
        query: { title: "新增案件管理", type: "add" },
      });
    },
    //编辑
    onedit(row) {
      this.$router.push({
        path: "/caseManage/addcaseManage",
        query: { title: "编辑案件管理", type: "edit", id: row.id },
      });
    },
    onExport(row) {
      $download(`/system/case/export/${row.id}`, {}, `${row.caseNo}.pdf`);
    },
    //删除
    ondel(row) {
      this.$modal
        .confirm("是否确认删除" + row.caseName + '"的数据项？')
        .then(() => {
          delcustomer(row.customerId).then((res) => {
            this.getList();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});
    },
    // 查看
    onLook(id) {
      this.chivedDialog = true;
      casesList(id).then((res) => {
        console.log(res);
        this.archivedList = res.rows;
      });
    },
    //财务信息
    openModal(refname, row, type = 1) {
      this.$refs[refname].open(row, type);
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/case/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.uploading = false;
      this.getList();
    },
    handleFileError(error, file, fileList) {
      console.log(error, file, fileList);
    },
    // 提交上传文件
    submitFileForm() {
      this.uploading = true;
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.header {
  margin-bottom: 20px;
}
.isConflict {
  color: red;
}
</style>
